package com.qinsoft.frame.utils;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import com.qinsoft.frame.exception.ApiException;
import com.qinsoft.frame.messages.WriteMessage;
import com.taobao.api.TaobaoResponse;
import com.taobao.api.internal.mapping.Converter;
import com.taobao.api.internal.parser.json.JsonConverter;

public class TaobaoInter {
    /**
     * @param <T>
     * @param tql          TQL语句
     * @param clazz        返回类型
     * @return
     * @throws CallApiException 
     */
    public static <T extends TaobaoResponse> T sendInter(String tql, Class<T> clazz) throws ApiException
    {
        //String sessionKey  = UserUtil.getInstance().getUserInfo(WebContextFactory.get().getSession().getId()).getSessionKey();
        String sessionKey = "6200e02246ZZ68ff3c7d87d5a40f61670ee570ee5ea89f0845594270";
        return sendInter(tql, sessionKey, clazz, null);
    }
     /**
     * @param <T>
     * @param tql          TQL语句
     * @param clazz        返回类型
     * @param map          参数集
     * @return
     * @throws CallApiException 
     */
    public static <T extends TaobaoResponse> T sendInter(String tql, Class<T> clazz, Map<String,Object> map) throws ApiException
    {
        //String sessionKey  = UserUtil.getInstance().getUserInfo(WebContextFactory.get().getSession().getId()).getSessionKey();
        String sessionKey = "6200e02246ZZ68ff3c7d87d5a40f61670ee570ee5ea89f0845594270";
        return sendInter(tql, sessionKey, clazz, map);
    }

    /**
     * @param <T>
     * @param tql           TQL语句
     * @param sessionKey    sessionKey
     * @param clazz         返回类型
     * @return
     * @throws CallApiException 
     */
    public static <T extends TaobaoResponse> T sendInter(String tql, String sessionKey, Class<T> clazz) throws ApiException
    {
        return sendInter(tql, sessionKey, clazz, null);
    }

	/**
	 * @param <T>
	 * @param tql          TQL语句
	 * @param sessionKey   sessionKey
	 * @param clazz        返回类型
	 * @param map          参数集
	 * @return
	 * @throws ApiException 
	 */
    public static <T extends TaobaoResponse> T sendInter(String tql, String sessionKey, Class<T> clazz, Map<String,Object> map) throws ApiException
    {
		T response = null;
		try 
		{
		    String result = execute(tql,sessionKey,map);
			Converter con = new JsonConverter();
			response = con.toResponse(result, clazz);
			response.setBody(result);
		} 
		catch (Exception e) 
		{
			WriteMessage.WriteErrorLog("com.qinsoft.frame.utils.TaobaoInter.sendInter()", e);
		}
		if(!response.isSuccess())
		{
		    if(response.getSubMsg()==null){
		        throw new ApiException(response.getMsg());
		    }
            else{
                throw new ApiException(response.getSubMsg());
            }
		}
		return response;
	}
	/**
     * @param <T>
     * @param tql           TQL语句
     * @param sessionKey    sessionKey
     * @param clazz         返回类型
     * @return
     * @throws CallApiException 
     */
    public static String execute(String tql, String sessionKey, Map<String,Object> map){
        Map<String,Object> params = new HashMap<String,Object>();
        params.put("ql", tql);
        params.put("app_key", QinConfig.getInstance("taobao").getValue("appkey"));
        params.put("session", sessionKey);
        if(map!=null)
        {
            Set<Map.Entry<String, Object>> set = map.entrySet();
            for (Iterator<Map.Entry<String, Object>> it = set.iterator(); it.hasNext();) 
            {
                Map.Entry<String, Object> entry = (Map.Entry<String, Object>) it.next();
                params.put(entry.getKey(), entry.getValue());
            }
        }
        params.put("sign_method", "md5");
        byte[] result = HttpRequestUtil.sendRequestV1(QinConfig.getInstance("taobao").getValue("tqlurl"),params,QinConfig.getInstance("taobao").getValue("secret"),"post",null,"UTF-8",null,null,null);
        String rs = null;
        try
        {
            rs = new String(result,"utf-8");
            System.out.println(rs);
        }
        catch (UnsupportedEncodingException e)
        {
            WriteMessage.WriteErrorLog("com.qinsoft.frame.utils.TaobaoInter.execute()", e);
        }
        return rs;
    }
}
